package com.example.news;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.TaskInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;

import com.example.news.dao.HistoryDao;
import com.example.news.entity.History;
import com.example.news.entity.News;
import com.example.news.entity.Userinfo;
import com.google.gson.Gson;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * @author Admin
 */
public class NewsDetailsActivity extends AppCompatActivity implements View.OnClickListener {


    private static final String TAG = "NewsDetailsActivity-Log";
    private News.ResultDTO.DataDTO dataDTO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_details);
        // 获取传递的数据


        Toolbar toolbar = findViewById(R.id.toolbar);
        WebView webView = findViewById(R.id.webView);

        dataDTO = (News.ResultDTO.DataDTO) getIntent().getSerializableExtra(TabNewsFragment.DATA_DTO);

        if (Objects.nonNull(dataDTO)) {
            saveHisotry(dataDTO);
            toolbar.setTitle(dataDTO.getTitle());
            webView.loadUrl(dataDTO.getUrl());
        }
        toolbar.setOnClickListener(this);
    }

    private void saveHisotry(News.ResultDTO.DataDTO dataDTO) {
        Userinfo userinfo = Userinfo.getUserinfo();
        if (Objects.isNull(userinfo)) {
            return;
        }
        String uniquekey = dataDTO.getUniquekey();
        boolean count = HistoryDao.queryHasSave(uniquekey, userinfo.getUserName());
        if(count){
            long save = HistoryDao.saveHistory(uniquekey, userinfo.getUserName(), new Gson().toJson(dataDTO));
            Log.d(TAG, "onCreate: save " + save);
        }
//        long count = History.count(History.class, "uniquekey=? and user_name=?", new String[]{uniquekey, userinfo.getUserName()});
//        Log.d(TAG, "onCreate: uniquekey "+ uniquekey+" count " + count);
//        if(count==0){
//            long save = History.save(new History(uniquekey, userinfo.getUserName(), new Gson().toJson(dataDTO)));
//            Log.d(TAG, "onCreate: save " + save);
//        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.toolbar){
            // 详情页，直接销毁掉，不要去跳转
            finish();
        }
    }

}